<?php

namespace App\Http\Controllers\Admin;

use App\Models\BookHomeManageShop;
use App\Models\Manage;
use App\Validate\ManageInfoValidate;
use Illuminate\Support\Facades\DB;

class ManageController extends CommonController
{
    public $model = null;
    protected $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new Manage();
        $this->validate = new ManageInfoValidate();
    }

    /**
     * 筛选(用于下拉框选择)
     * @param type  类型  空或0表示获取全部  1 只获取图书到家相关管理员  2 只查询下级管理员
     */
    public function filterList()
    {
        $type = $this->request->type;
        $shop_all_id = '';
        $manage_id_all = '';
        if ($type == 1) {
            $shop_all_id = $this->getAdminShopIdAll();
            if (empty($shop_all_id)) {
                return $this->returnApi(203, '暂无数据'); //无权限访问
            }
        } elseif ($type == 2) {
            //查看所有下级管理员id
            $manageModelObj = new Manage();
            $manage_id_all = $manageModelObj->getManageIdAll(request()->manage_id);
        }
        $data = $this->model->getFilterLists(['id', Manage::$manage_name . ' as username', 'account'], $shop_all_id, $manage_id_all);

        if ($data) {
            return $this->returnApi(200, '获取成功', true, $data);
        }
        return $this->returnApi(203, '暂无数据');
    }


    /**
     * 管理员列表
     * @param keywords 关键字搜索
     * @param page 页数    默认第一页
     * @param limit 限制条数  默认 10
     * @param start_time 开始时间
     * @param end_time 结束时间
     */
    public function lists()
    {
        $keywords = $this->request->input('keywords', '');
        $start_time = $this->request->input('start_time', '');
        $end_time = $this->request->input('end_time', '');
        $limit = $this->request->input('limit', 10);
        $page = $this->request->input('page', 1);

        //查看所有下级管理员id
        $manageModelObj = new Manage();
        $manage_id_all = $manageModelObj->getManageIdAll(request()->manage_id);

        $res = $this->model->lists($keywords, $manage_id_all, $start_time, $end_time, $limit);

        if ($res['data']) {
            $res = $this->disPageData($res);
            foreach ($res['data'] as $key => &$val) {
                $role_name = '';
                $role_id = [];
                foreach ($val['con_role'] as $k => $v) {
                    $role_name .= ',' . $v['role_name'];
                    $role_id[] = $v['id'];
                }
                $res['data'][$key]['role_name'] = trim($role_name, ',');
                $res['data'][$key]['role_id'] = $role_id;
                unset($val['con_role']);
                //增加序号
                $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);
            }

            return $this->returnApi(200, '获取成功', true, $res);
        }

        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 管理员详情
     * @param id  管理员id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        //查看所有下级管理员id
        $manageModelObj = new Manage();
        $manage_id_all = $manageModelObj->getManageIdAll(request()->manage_id);

        $res = $this->model->detail($this->request->id, $manage_id_all);

        if (empty($res)) {
            return $this->returnApi(203, "暂无数据");
        }
        return $this->returnApi(200, "获取成功", true, $res->toArray());
    }


    /**
     * 管理员添加
     * @param account 账号，不能存在中文  只能是中文或数字    必填
     * @param username 姓名至少2位数         必填
     * @param password 密码 中文加英文   6-20 位之间     必填
     * @param confirm_password 密码 中文加英文   6-20 位之间    必填
     * @param role_ids 角色id  多个 逗号 拼接    选填
     * @param tel 电话号码
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        //验证密码
        $validate_password = validate_password($this->request->password);
        if ($validate_password !== true) {
            return $this->returnApi(201,  $validate_password);
        }

        //判断电话号码是否符合要求
        if (!empty($this->request->tel) && !verify_tel($this->request->tel)) {
            return $this->returnApi(201,  '电话号码格式不正确');
        }

        $is_exists = $this->model->nameIsExists($this->request->account, 'account');

        if ($is_exists) {
            return $this->returnApi(202, "该管理员已存在");
        }


        DB::beginTransaction();
        try {
            $res = $this->model->add($this->request);

            DB::commit();
            return $this->returnApi(200, '添加成功', true);
        } catch (\Exception $e) {
            // echo $e->getMessage();
            DB::rollBack();
            return $this->returnApi(202, '添加失败');
        }
    }

    /**
     * 管理员修改
     * @param id 管理员id
     * @param username 姓名至少2位数   必填
     * @param tel 电话号码
     * @param role_ids 角色id  多个 逗号 拼接    选填
     */
    public function change()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        if ($this->request->id == 1 || $this->request->id == $this->request->manage_id) {
            return $this->returnApi(201,  '此账号不允许修改');
        }

        //判断电话号码是否符合要求
        if (!empty($this->request->tel) && !verify_tel($this->request->tel)) {
            return $this->returnApi(201,  '电话号码格式不正确');
        }

        $is_exists = $this->model->nameIsExists($this->request->account, 'account', $this->request->id);
        if ($is_exists) {
            return $this->returnApi(202, "该管理员已存在");
        }
        DB::beginTransaction();
        try {
            $res = $this->model->change($this->request);

            DB::commit();
            return $this->returnApi(200, '编辑成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, '编辑失败');
        }
    }

    /**
     * 管理员删除
     * @param id  管理员id  必选
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        if ($this->request->id == 1 || $this->request->id == $this->request->manage_id) {
            return $this->returnApi(201,  '此账号不允许修改');
        }

        $res = $this->model->del($this->request->id);

        if ($res === true) {
            return $this->returnApi(200, "删除成功", true);
        }
        return $this->returnApi(202, $res);
    }

    /**
     * 管理员修改密码
     * @param id  管理员id  必选
     * @param password 密码 中文加英文   6-20 位之间     必填
     * @param confirm_password 密码 中文加英文   6-20 位之间    必填
     */
    public function manageChangePwd()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('manage_change_pwd')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        //验证密码
        $validate_password = validate_password($this->request->password);
        if ($validate_password !== true) {
            return $this->returnApi(201, $validate_password);
        }

        $res = $this->model->where('is_del', 1)->find($this->request->id);
        if (empty($res)) {
            return $this->returnApi(202, '修改失败');
        }
        $res->password = md5($this->request->password);
        $result = $res->save();

        if ($result) {
            return $this->returnApi(200, '修改成功', true);
        }

        return $this->returnApi(202, '修改失败');
    }


    /**
     * 管理员修改自己密码
     * @param token  管理员token  必选
     * @param password 密码 中文加英文   6-20 位之间     必填
     * @param confirm_password 密码 中文加英文   6-20 位之间    必填
     */
    public function manageChangeSelfPwd()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('manage_change_self_pwd')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        //验证密码
        $validate_password = validate_password($this->request->password);
        if ($validate_password !== true) {
            return $validate_password;
        }

        $res = $this->model->where('is_del', 1)->find($this->request->manage_id);
        if (empty($res)) {
            return $this->returnApi(202, '修改失败');
        }
        $res->password = md5($this->request->password);
        $result = $res->save();

        if ($result) {
            return $this->returnApi(200, '修改成功', true);
        }

        return $this->returnApi(202, '修改失败');
    }
}
